package org.gp.core.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.gp.core.entity.Blacklist;
import org.gp.core.entity.User;
import org.gp.core.entity.dto.ResponseDTO;
import org.gp.core.entity.enums.DTOCodeEnum;
import org.gp.core.mapper.BlacklistMapper;
import org.gp.core.mapper.UserMapper;
import org.gp.core.service.IBlacklistService;
import org.gp.core.service.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 黑名单表  服务实现类
 * </p>
 *
 * @author LuoLiang
 * @since 2017-03-14
 */
@Service
@Slf4j
public class BlacklistServiceImpl extends ServiceImpl<BlacklistMapper, Blacklist> implements IBlacklistService {
    @Resource
    private IUserService userService;
    @Resource
    private UserMapper userMapper;
    @Value("${be.username}")
    private String admin;

    @Override
    public ResponseDTO<List<User>> getBlackList(Integer currentPage, Integer pageSize) {
        ResponseDTO<List<User>> dto = new ResponseDTO<>();

        //分页参数构造
        Page<User> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);

        try {
            List<User> userList = userMapper.selectUserBlackList(page);

            dto.setData(userList);
            dto.setCode(DTOCodeEnum.SUCCESS.getDesc());
            dto.setResMsg(page.getTotal() + "_" + page.getCurrent());
        } catch (Exception e) {
            log.error("获取黑名单用户业务失败：", e);
            dto.setCode(DTOCodeEnum.FAIL.getDesc());
            dto.setResMsg("获取黑名单用户失败");
        }

        return dto;
    }

    @Override
    public ResponseDTO addUser(Integer userId, String reason) {
        ResponseDTO dto = new ResponseDTO();

        Blacklist blacklist = new Blacklist();
        blacklist.setUserId(userId);
        blacklist.setReason(reason);
        blacklist.setOperator(admin);

        try {
            insert(blacklist);

            dto.setCode(DTOCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            log.error("加入黑名单业务异常{}，失败用户Id={}", e, userId);
            dto.setCode(DTOCodeEnum.FAIL.getDesc());
            dto.setResMsg("把用户加入黑名单失败");
        }

        return dto;
    }

    @Override
    public ResponseDTO removeUser(Integer userId) {
        ResponseDTO dto = new ResponseDTO();

        EntityWrapper<Blacklist> ew = new EntityWrapper<>();
        ew.where("user_id={0}", userId);

        try {
            delete(ew);

            dto.setCode(DTOCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            log.error("移出黑名单业务异常{}，失败用户Id={}", e, userId);
            dto.setCode(DTOCodeEnum.FAIL.getDesc());
            dto.setResMsg("把用户移出黑名单失败");
        }

        return dto;
    }


}
